#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os

import numpy as np
from model_service.pytorch_model_service import PTServingBaseService
# import joblib
# from sklearn.externals import joblib
# import pickle
import lightgbm as lgb

class PredictService(PTServingBaseService):
    def __init__(self, model_name, model_path):
        super(PredictService, self).__init__(model_name,model_path)
        dir_path = os.path.dirname(os.path.realpath(model_path))
        model_path = os.path.join(dir_path, 'lgbm.txt')
        print('Opening,',model_path)

        # sk_model = joblib.load(model_path)
        # pkl_file = open(model_path, 'rb')
        # sk_model = pickle.load(pkl_file)
        sk_model = lgb.Booster(model_file=model_path)

        print(sk_model)
        self.model = sk_model
        self.load_preprocess()

    def load_preprocess(self, mean_name='mean.npy', std_name='std.npy'):
        dir_path = os.path.dirname(os.path.realpath(self.model_path))

        mean_path = os.path.join(dir_path, mean_name)
        std_path = os.path.join(dir_path, std_name)
        self.mean = np.load(mean_path)
        self.std = np.load(std_path)

    def _preprocess(self, data):
        print('pre_data:{}'.format(data))
        preprocessed_data = {}

        for d in data:
            for k, v in data.items():
                for file_name, features_path in v.items():
                    x = np.load(features_path)
                    # deploy environment numpy version
                    x = (x - self.mean) / self.std
                    x = np.nan_to_num(x)
                    x[x > 1000000] = 0
                    x[x < -1000000] = 0
                    preprocessed_data[k] = x
        return preprocessed_data

    def _postprocess(self, data):
        print('post_data:{}'.format(data))
        infer_output = {}

        # for result in data:
        infer_output['scores'] = data.tolist()

        return infer_output

    def _inference(self, data):
        print('infer data',data)
        input_data = data['features']
        pre_result = self.model.predict([input_data])
        return pre_result
